package com.gitee.zw.irmp.common.utils;

import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.exception.ObsException;
import com.obs.services.model.DeleteObjectResult;
import com.obs.services.model.ObsBucket;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import jakarta.annotation.PostConstruct;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

@Component
@ConditionalOnClass(ObsClient.class)
@Slf4j
@ConfigurationProperties(prefix = "app.irmp.common.huawei-cloud.obs")
public class ObsBucketUtils {
    @Setter private String accessKey;
    @Setter private String secretKey;
    @Setter private String endPoint;
    @Setter private String location;

    ObsClient obsClient;
    @PostConstruct
    public void initClient() throws ObsException {
        ObsConfiguration config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(endPoint);

        ObsClient obsClient = new ObsClient(accessKey, secretKey, config);
        ObsBucket obsBucket = new ObsBucket();
        obsBucket.setLocation(location);
//        obsBucket.setBucketName(bucketName);
//        obsClient.createBucket(obsBucket);
        log.info("Create bucket: {} successfully!", location);
        this.obsClient = obsClient;
    }

    /**
    * 上传文件到指定的位置
     * @param localFile 本地文件
     * @param   path 上传到OBS的相对路径
     * @param bucketName OBS桶名
     * @return objectKey
     */
    public String upload(File localFile, String path, String bucketName) throws Exception {
        PutObjectResult rst = obsClient.putObject(bucketName, path, localFile);
        log.info("Upload file {} to obs {}  successfully!", localFile.getName(), rst.getObjectKey());
        return rst.getObjectKey();
    }

    /**
     *
     * @param objectKey OBS文件名
     * @param localFile 用于写入下载内容的本地文件
     * @param bucketName OBS桶名
     * @throws Exception
     */
    public void download(String objectKey, File localFile, String bucketName) throws Exception {
        ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null);
        try(InputStream is = obsObject.getObjectContent()){
            FileUtils.copyInputStreamToFile(is, localFile);
        }
    }

    /**
     *
     * @param objectKey OBS文件名
     * @param bucketName OBS桶名
     * @throws Exception
     */
    public void delete(String objectKey, String bucketName) throws Exception {
        DeleteObjectResult deleteObjectResult = obsClient.deleteObject(bucketName, objectKey);
        log.info("Delete obs file: {} successfully!", deleteObjectResult.getObjectKey());
    }

}
